package index

import (
	"context"
	"hotgo/addons/hgexample/model/input/sysin"
	epService "hotgo/addons/hgexample/service"
	"hotgo/api/api/index"
	"hotgo/internal/consts"
	"hotgo/internal/dao"
	"hotgo/internal/library/contexts"
	"hotgo/internal/library/nickname"
	"hotgo/internal/library/token"
	"hotgo/internal/library/wechat"
	"hotgo/internal/model"
	"hotgo/internal/model/entity"
	"hotgo/internal/service"

	"github.com/gogf/gf/v2/crypto/gmd5"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/gogf/gf/v2/util/grand"
)

var (
	Index = cIndex{}
)

type cIndex struct{}

func (c *cIndex) Index(ctx context.Context, req *index.IndexReq) (res *index.IndexRes, err error) {
	//获取Banner
	banner, _, _ := epService.SysEpBanner().List(ctx, &sysin.EpBannerListInp{})
	//获取系统配置
	config, _ := service.SysConfig().GetBasic(ctx)

	res = &index.IndexRes{
		Banner: banner,
		Config: config,
	}
	return
}

func (c *cIndex) GetCode(ctx context.Context, req *index.GetCodeReq) (res *index.GetCodeRes, err error) {
	auth, err := wechat.NewMiniProgram(ctx).GetAuth().Code2Session(req.Code)
	if err != nil {
		err = gerror.New(err.Error())
		return
	}
	res = new(index.GetCodeRes)
	res.OpenId = auth.OpenID
	return
}
func (c *cIndex) GetUser(ctx context.Context, req *index.GetUserReq) (res *index.GetUserRes, err error) {
	res = new(index.GetUserRes)
	res.Data = contexts.GetUser(ctx)
	return
}
func (c *cIndex) SaveUser(ctx context.Context, req *index.SetUserReq) (res *index.SetUserRes, err error) {
	userId := int64(0)
	userOauthRecords, _ := dao.EpMemberOauth.Ctx(ctx).Where(dao.EpMemberOauth.Columns().OauthOpenid, req.OpenId).All()
	for _, v := range userOauthRecords {
		if gconv.String(v["oauth_client"]) == req.Platform {
			userId = gconv.Int64(v["member_id"])
			break
		}
	}

	userRecord := gdb.Record{}
	if userId > 0 {
		userRecord, _ = dao.EpMember.Ctx(ctx).Where(dao.EpMember.Columns().Id, userId).One()
	}
	//用户信息
	if userRecord.IsEmpty() {
		userData := &entity.EpMember{
			NickName:   nickname.GenerateName(),
			UserName:   grand.Letters(8),
			Salt:       grand.S(6),
			InviteCode: grand.S(12),
			Sex:        1,
			Avatar:     "/resource/image/1.webp",
		}
		userData.PasswordHash = gmd5.MustEncryptString(grand.Letters(8) + userData.Salt)
		userResult, _ := dao.EpMember.Ctx(ctx).Data(userData).Insert()
		userId, _ = userResult.LastInsertId()
		dao.EpMemberOauth.Ctx(ctx).Data(g.Map{
			"member_id":    userId,
			"oauth_client": req.Platform,
			"oauth_openid": req.OpenId,
		}).Replace()
	}
	userRecord, _ = dao.EpMember.Ctx(ctx).Where(dao.EpMember.Columns().Id, userId).One()
	user := &model.Identity{
		Id:       gconv.Int64(userRecord[dao.EpMember.Columns().Id]),
		Username: gconv.String(userRecord[dao.EpMember.Columns().UserName]),
		RealName: gconv.String(userRecord[dao.EpMember.Columns().NickName]),
		App:      consts.AppApi,
		LoginAt:  gtime.Now(),
	}

	lt, expires, err := token.Login(ctx, user)
	res = new(index.SetUserRes)
	res.OpenId = req.OpenId
	res.Token = lt
	res.Expires = expires
	return
}
